import * as dd from "dingtalk-jsapi"; // 此方式为整体加载，也可按需进行加载
import * as api from "@/api/api";

export const setAuth = async (config = {}) => {
  try {
    const { url = window.location.href, agentId, corpId } = config;
    const params = { url };
    const res = await api.default.GetDingDingConfig(params);
    
    if (!res?.timeStamp || !res?.nonceStr || !res?.signature) {
      throw new Error('Invalid DingDing config response');
    }

    return new Promise((resolve, reject) => {
      dd.ready(() => {
        dd.config({
          agentId: agentId || "3779256012",
          corpId: corpId || "ding367b78bec5ac2921ee0f45d8e4f7c288",
          timeStamp: res.timeStamp,
          nonceStr: res.nonceStr,
          signature: res.signature,
          type: 0,
          jsApiList: [
            "runtime.info",
            "biz.contact.choose",
            "device.notification.confirm",
            "device.notification.alert",
            "device.notification.prompt",
            "biz.ding.post",
            "biz.util.openLink",
          ],
        });
        resolve();
      });

      dd.error(reject);
    });
  } catch (error) {
    console.error('setAuth failed:', error);
    throw error;
  }
};
export const getToken = async (corpId) => {
  // if (uni.getStorageSync("TrainManageXizang-Admin-Token")) {
  //   return true;
  // }

  return new Promise((resolve, reject) => {
    dd.ready(() => {
      dd.runtime.permission.requestAuthCode({
        corpId: corpId || "ding367b78bec5ac2921ee0f45d8e4f7c288",
        onSuccess: async (info) => {
          try {
            const params = { code: info.code };
            const res = await api.default.LoginByDingCode(params);
            
            if (res?.tokenModel?.accessToken) {
              uni.setStorageSync("TrainManageXizang-Admin-Token", res.tokenModel.accessToken);
              resolve(true);
            } else {
              reject(new Error("No access token received"));
            }
          } catch (error) {
            reject(error);
          }
        },
        onFail: (err) => {
          reject(err);
        }
      });
    });

    dd.error((err) => {
      reject(err);
    });
  });
};



export const getUserInfo = async (userId) => {
  // if (localStorage.getItem("TrainManageXizang-Admin-Token")) {
  //   return true
  // }
  if(!userId ){ return false}
  let params = {
    userId: userId
  }
  let res = await api.default.LoginByUserId(params);
  if (res?.tokenModel?.accessToken) {
    localStorage.setItem(
      "TrainManageXizang-Admin-Token",
      res.tokenModel.accessToken
    );
    return true
  }
  console.log(11, res)
}